package cn.ecpay.unionpay.settle.controller;

import cn.ecpay.unionpay.settle.Common.RespCode;
import cn.ecpay.unionpay.settle.dao.QuotaReductionDao;
import cn.ecpay.unionpay.settle.entity.db.TPvQuotaReduction;
import cn.ecpay.unionpay.settle.entity.db.TPvSingleQuery;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import cn.ecpay.unionpay.settle.util.SDKConfig;
import org.rex.db.exception.DBException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 额度调减
 * Created by zhaoyanzeng on 2018/11/6.
 */
@RestController
public class QuotaReductionController {

    @Resource
    private QuotaReductionDao quotaReductionDao;

    @RequestMapping(value = "/quotaReduction", method = RequestMethod.POST)
    protected String quotaReduction(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Map<String, String> contentData = convertContentData(req);
        if(isExistTxn(contentData.get("txnNo"),contentData.get("txnDate"))){
            return "重复交易";
        }
        TPvQuotaReduction quotaReduction = new TPvQuotaReduction();
        Map<String, String> reqData = FsasService.sign(contentData, CommonBase.encoding);
        reqDataConvert(quotaReduction,reqData);
        String requestBackUrl = SDKConfig.getConfig().getBackRequestUrl();
        Map<String, String> rspData = FsasService.doPost(reqData,requestBackUrl, CommonBase.encoding);
        rspDataConvert(quotaReduction,rspData);
        StringBuffer parseStr = new StringBuffer("");
        if(!rspData.isEmpty()){
            if(FsasService.validate(rspData, CommonBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                quotaReduction.setRespValidate("1");
                String respCode = rspData.get("respCode") ;
                if(RespCode.RESP_SUCCESS.equals(respCode)){
                    //成功
                    //TODO
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                quotaReduction.setRespValidate("0");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        try {
            quotaReductionDao.insert(quotaReduction);
        } catch (DBException e) {
            LogUtil.writeErrorLog("保存额度调减失败");
            e.printStackTrace();
        }
        String reqMessage = CommonBase.genHtmlResult(reqData);
        String rspMessage = CommonBase.genHtmlResult(rspData);
        return "额度调减请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+parseStr;
    }


    private Map<String, String> convertContentData(HttpServletRequest req) {
        String acqInsCode = req.getParameter("acqInsCode");
        String txnNo = req.getParameter("txnNo");
        String txnDate = req.getParameter("txnDate");
        String txnAmt = req.getParameter("txnAmt");
        Map<String, String> contentData = new HashMap<String, String>();
        contentData.put("version", CommonBase.version);                  //版本号
        contentData.put("encoding", CommonBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "51");                                   //交易类型 51 额度调减
        contentData.put("txnAmt", txnAmt);                                    //调整额度
        contentData.put("currencyCode", "156");                                    //币种
        contentData.put("acqInsCode", acqInsCode);                        //机构代码
        contentData.put("txnNo", txnNo);                                    //交易流水号
        contentData.put("txnDate",txnDate);                               //交易日期
        contentData.put("sndTime", CommonBase.getSendTime());      //发送时间 格式HHmmss
        return contentData;
    }

    //申请参数
    private void reqDataConvert(TPvQuotaReduction quotaReduction, Map<String, String> reqData) {
        quotaReduction.setTxnNo(reqData.get("txnNo"));
        quotaReduction.setTxnType(reqData.get("txnType"));
        quotaReduction.setAcqInsCode(reqData.get("acqInsCode"));
        quotaReduction.setTxnDate(reqData.get("txnDate"));
        quotaReduction.setSndTime(reqData.get("sndTime"));
        quotaReduction.setCurrencyCode(reqData.get("currencyCode"));
        quotaReduction.setTxnAmt(reqData.get("txnAmt"));
        quotaReduction.setRemark(reqData.get("remark"));

    }

    //同步返回结果
    private void rspDataConvert(TPvQuotaReduction quotaReduction,Map<String, String> rspData) {
        quotaReduction.setRespCode(rspData.get("respCode"));
        quotaReduction.setRespMsg(rspData.get("respMsg"));
        quotaReduction.setAvlbQuotaAmt(rspData.get("avlbQuotaAmt"));
    }

    /**
     * 交易是否已存在
     *
     * @return
     */
    public boolean isExistTxn(String txnNo, String txnDate) {
        try {
            return quotaReductionDao.isExistTxn(txnNo, txnDate);
        } catch (DBException e) {
            e.printStackTrace();
            return false;
        }
    }
}
